<?php
session_start();
require 'db_connect.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(['success' => false, 'error' => '无效请求方法']));
}

// 获取当前用户ID
$userID = $_SESSION['userId'];
if (!$userID) {
    http_response_code(401);
    die(json_encode(['success' => false, 'error' => '未登录']));
}

// 获取旧密码
$data = json_decode(file_get_contents('php://input'), true);
$oldPassword = $data['oldPassword'] ?? '';

// 查询数据库中的哈希密码
$stmt = $conn->prepare("SELECT Password FROM User WHERE UserID = ?");
$stmt->bind_param("i", $userID);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();

if (!$result) {
    die(json_encode(['success' => false, 'error' => '用户不存在']));
}

// 验证旧密码
if (password_verify($oldPassword, $result['Password'])) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'error' => '旧密码错误']);
}